package com.project.nimsen.web.pub.tools;

import java.io.BufferedReader;
import java.io.File;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.project.jdbc.utils.ClassUtils;
import com.project.jdbc.web.BaseMVCAction;
import com.project.nimsen.cache.ManCacheManager;
import com.project.nimsen.constant.ModelConstant;
import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.entity.Qrcodecard;
import com.project.nimsen.entity.Site;
import com.project.nimsen.service.IQrcodecardService;
import com.project.nimsen.util.NimsenUtil;
import com.project.nimsen.util.WebUtil;
import com.project.nimsen.util.ZxingUtil;

/**
 * 关于二维码的工具
 * */
@Controller
@RequestMapping(value ="/pub/tools/qrcode")
public class ToolsQRcode extends BaseMVCAction {
	@RequestMapping(value ="/reqDemo")
	public void reqDemo(HttpServletRequest req, HttpServletResponse res){
		try{
			BufferedReader reader = req.getReader();
			StringBuffer json_str = new StringBuffer();
			String str_tmp=null;
			while(StringUtils.isNotBlank(str_tmp=reader.readLine())){
				json_str.append(str_tmp);
			}
			System.out.println(json_str.toString());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	@RequestMapping(value ="/cachetest")
	public void cachetest(){
		Cache<String, Object> cache = cacheMan.getCache("testcache");
		Object boj = cache.get("testkey");
		if(boj==null){
			cache.put("testkey", "this is cachemanager test");
			boj = cache.get("testkey");
		}
		System.out.println(NimsenUtil.obj2String(boj));
	}
	@Resource
	ManCacheManager cacheMan;
	@Resource
	WebUtil webUtil;
	@Resource
	IQrcodecardService qrcodecardService;
	/**
	 * 二维码名片地址
	 * */
	@RequestMapping(value ="/card")
	public String card(HttpServletRequest request){
		HttpSession session = request.getSession();
		//用户访问的终端
		String access_terminal = NimsenUtil.obj2String(session.getAttribute("access_terminal"));
		//如果是pc端的情况
		if(ModelConstant.PC.equals(access_terminal)){
			return "/themes/404";
		}
		return "/WEB-INF/tools/qrcode/card_phone";
	}
	/**
	 * 制作二维码名片
	 * */
	@RequestMapping(value ="/card_make")
	public void card_make(HttpServletRequest request, @RequestParam(value="phone") String phone,
		@RequestParam(value="bak") String bak,@RequestParam(value="email") String email,
		@RequestParam(value="address") String address,@RequestParam(value="duty") String duty,
		@RequestParam(value="name") String name,@RequestParam(value="company") String company,
		@RequestParam(value="modelphone") String modelphone,@RequestParam(value="perhomepage") String perhomepage,
		@RequestParam(value="logo") MultipartFile uploadFile,
		HttpServletResponse response){
		try {
			Site site = webUtil.currSite(request);
			Qrcodecard card = qrcodecardService.findByphone(modelphone, site.getId());
			
			if(card==null&&StringUtils.isNotBlank(phone))
				card = qrcodecardService.findByphone(phone, site.getId());
			
			if(card==null){
				card = new Qrcodecard();
				card.setActive(0);
				card.setCreateTime(new Date());
				card.setSiteid(site.getId());
			}
			card.setCaddress(address);
			card.setCbak(bak);
			card.setCduty(duty);
			card.setCemail(email);
			card.setCmodelphone(modelphone);
			card.setCname(name);
			card.setCompany(company);
			card.setCperhomepage(perhomepage);
			card.setCphone(phone);
			if(StringUtils.isNotBlank(card.getId()))
				qrcodecardService.update(card);
			else
				qrcodecardService.save(card);
			
			
			//设置输出信息
			response.setContentType("image/jpeg");
			response.setHeader("Pragma","no-cache");
			response.setHeader("Cache-Control","no-cache");
			response.setIntHeader("Expires",-1);
			int width = 600;
			int height = 600;
			//转换过后的信息
			String content = obj2qrcodestr(card);
			File file = new File(uploadFile.getOriginalFilename());
			if(StringUtils.isBlank(file.getName()))
				ZxingUtil.encodePR(content, width, height, response.getOutputStream());
			else{
				ServletContext sevcon = request.getSession().getServletContext();
				String allPath = sevcon.getRealPath(File.separator+NimsenConstant.UPLOAD_PATH);
				File dir = new File(allPath);
				if (!dir.exists())
					dir.mkdirs();
				String filename = file.getName();
				String autoFilename = ClassUtils.autoUUID() + filename.substring(filename.lastIndexOf("."));
				File tempfile = new File(allPath+File.separator+autoFilename);
				
				FileCopyUtils.copy(uploadFile.getBytes(), tempfile);
				ZxingUtil.encodePR(content, width, height, response.getOutputStream(), tempfile);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 把对象转换成要制作的二维码信息
	 * */
	private String obj2qrcodestr(Qrcodecard qrcode){
		StringBuffer sbf = new StringBuffer("BEGIN:VCARD \nVERSION:3.0");
		if(StringUtils.isNotBlank(qrcode.getCname()))
			sbf.append(" \nN:").append(qrcode.getCname());
		if(StringUtils.isNotBlank(qrcode.getCemail()))
			sbf.append(" \nEMAIL:").append(qrcode.getCemail());
		if(StringUtils.isNotBlank(qrcode.getCphone()))
			sbf.append(" \nTEL:").append(qrcode.getCphone());
		if(StringUtils.isNotBlank(qrcode.getCmodelphone()))
			sbf.append(" \nTEL;CELL:").append(qrcode.getCmodelphone());
		if(StringUtils.isNotBlank(qrcode.getCaddress()))
			sbf.append(" \nADR;WORK:").append(qrcode.getCaddress());
		if(StringUtils.isNotBlank(qrcode.getCompany()))
			sbf.append(" \nORG:").append(qrcode.getCompany());
		if(StringUtils.isNotBlank(qrcode.getCduty()))
			sbf.append(" \nTITLE:").append(qrcode.getCduty());
		if(StringUtils.isNotBlank(qrcode.getCperhomepage()))
			sbf.append(" \nURL:").append(qrcode.getCperhomepage());
		if(StringUtils.isNotBlank(qrcode.getCbak()))
			sbf.append(" \nNOTE:").append(qrcode.getCbak());
		sbf.append(" \nEND:VCARD");
		return sbf.toString();
	}
}